<template>
	<view class="baseForm">
		<u-loading-page :loading="loading"></u-loading-page>
		<view v-if="!loading" class="overhidden">
			<!-- 工单头部编号&状态样式 -->
			<view class="" style="width: 100%; background-color: rgba(22, 37, 78, 0.85); height: 110px">
				<view class="" style="padding: 22px 15px; display: flex; justify-content: space-between">
					<view class="" style="display: flex; flex-direction: column">
						<text style="font-size: 18px; color: #fff; font-weight: bold">
							{{ useDictionaryStore().filterDictName('RepairOrderStatus', taskInfo.orderStatus) }}
						</text>
						<text style="font-size: 15px; color: #fff; margin-top: 9px">报修编号：{{ taskInfo.orderNo }}</text>
					</view>
					<image v-show="props.isRead == 1" src="@/static/image/order.png" style="width: 50px; height: 50px" />
				</view>
			</view>

			<!-- 查看页面样式 -->
			<!-- <view v-if="props.isRead == 1" class="mt-10-"> -->
			<!-- 模具详情 -->
			<!-- <PlannedDeviceInfo :taskInfo="toRaw(taskInfo)"></PlannedDeviceInfo> -->
			<!-- 故障信息 -->
			<!-- <RepairOrderInfo :taskInfo="toRaw(taskInfo)"></RepairOrderInfo> -->
			<!-- 维修信息 -->
			<!-- <RepairHandleInfo :taskInfo="toRaw(taskInfo)"></RepairHandleInfo> -->
			<!-- </view> -->

			<!-- 编辑页面样式 -->
			<view class="mt-10-">
				<!-- bgColor="#0F40F5" -->
				<view class="repaire_tag_div">
					<view class="repaire_tag">
						<view class="tag_item" :class="tagCurrent === 0 ? 'active_tag' : ''" @click="selectTagHandle(0)">基础信息</view>
						<view class="tag_item" :class="tagCurrent === 1 ? 'active_tag' : ''" @click="selectTagHandle(1)">维修信息</view>
					</view>
				</view>
				<!-- <u-subsection :list="tabList" :current="tagCurrent" mode="subsection" activeColor="#0379FF" @change="sectionChange" class="repaireTag"></u-subsection> -->

				<u--form labelPosition="top" :model="taskInfo" :rules="rules" labelWidth="300" ref="uForm" class="form" errorType="toast">
					<!-- 模具详情 -->

					<view class="detail card" v-show="tagCurrent === 1 && props.isRead == 0">
						<view class="flex flex-col justify-between flex-1 h-full">
							<view class="record-content">
								<view class="flex title justify-between" style="margin: 6px 0 !important" @click="() => (isCollapse = !isCollapse)">
									<text>详细信息</text>
									<!-- <u-icon
										v-show="!isCollapse"
										name="arrow-up"
										color="#000a7b"></u-icon>
									<u-icon
										v-show="isCollapse"
										name="arrow-down"
										color="#000a7b"></u-icon> -->
								</view>
								<view style="margin-top: 8px">
									<u-form-item label="维修情况说明" prop="repairSituation" required>
										<u--textarea
											v-model="taskInfo.repairSituation"
											placeholder="维修请输入情况说明"
											height="40px"
											:customStyle="{
												marginTop: '2px'
											}"
										></u--textarea>
									</u-form-item>
									<u-form-item label="维修前图片" required prop="fixBeforeFiles">
										<upload-image
											:multiple="false"
											:accept="accept"
											@fileChange="getFixBeforeFiles"
											camera="back"
											:list="taskInfo.fixBeforeFiles"
											:capture="capture"
											:key="33"
											style="margin-top: 4px"
											folderName="eam/equ/eamPlannedMaintenance"
										></upload-image>
									</u-form-item>
									<u-form-item label="维修后图片" required prop="fixAfterFiles">
										<upload-image
											:multiple="false"
											:accept="accept"
											@fileChange="getFixAfterFiles"
											camera="back"
											:list="taskInfo.fixAfterFiles"
											:capture="capture"
											:key="22"
											style="margin-top: 4px"
											folderName="eam/equ/eamPlannedMaintenance"
										></upload-image>
									</u-form-item>
									<u-form-item label="维修中发现的其他问题" prop="otherProblem">
										<u--textarea
											v-model="taskInfo.otherProblem"
											placeholder="维修中发现的其他问题"
											height="40px"
											:customStyle="{
												marginTop: '2px'
											}"
										></u--textarea>
									</u-form-item>
									<u-form-item label="维修用时(h）" prop="repairUseTime" required>
										<view class="flex input-box1">
											<u--input v-model="taskInfo.repairUseTime" border="none" placeholder="请输入维修用时(h）" class="input-self"></u--input>
											<image @click.stop="clearInfo(['repairUseTime'])" v-show="taskInfo.repairUseTime" src="@/static/image/delete.png" />
										</view>
									</u-form-item>
									<!-- 									<u-form-item label="维修班组" prop="executeTeamId">
										<view class="flex input-box1">
											<u--input
												v-model="taskInfo.executeTeamName"
												border="none"
												disabled
												placeholder="请输入维修班组"
												class="input-self"></u--input>
											<!-- <image
                        @click.stop="
                          clearInfo(['executeTeamId', 'executeTeamName'])
                        "
                        v-show="taskInfo.faultPosition"
                        src="@/static/image/delete.png" /> 
										</view>
									</u-form-item> -->
									<u-form-item label="维修人员" prop="maintainUser" required>
										<u--textarea
											v-model="taskInfo.maintainUser"
											:rules="rules.maintainUser"
											placeholder="请输入维修人员"
											height="40px"
											:customStyle="{
												marginTop: '2px'
											}"
										></u--textarea>
										<!-- <view class="flex input-box1">
											<u--input
												v-model="person"
												:rules="rules.person"
												@click="showPersonPicker"
												border="none"
												placeholder="请选择维修人员"
												class="input-self"></u--input>
				
											<image
												@click.stop="
													clearInfo([
														'repairOrderPersons',
														'repairOrderPersons',
													])
												"
												v-show="taskInfo.repairOrderPersons"
												src="@/static/image/delete.png" />
										</view> -->
									</u-form-item>
								</view>
							</view>
						</view>
					</view>

					<PlannedDeviceInfo v-if="tagCurrent === 0" :taskInfo="taskInfo"></PlannedDeviceInfo>
					<!-- 基础信息 图片列表 -->
					<PlannedImageInfo v-if="tagCurrent === 0" :taskInfo="planDto"></PlannedImageInfo>

					<PlannedHandleInfo v-show="tagCurrent === 1 && props.isRead == 1" :taskInfo="taskInfo"></PlannedHandleInfo>

					<!-- 维修信息 -->
					<view v-show="tagCurrent === 1 && props.isRead == 0" class="detail card">
						<view class="flex flex-col justify-between flex-1 h-full">
							<view class="record-content">
								<view class="flex title justify-between" style="margin: 6px 0 !important">
									<text>备件更换</text>
								</view>
							</view>
							<view class="record-item">
								<view v-for="(item, index) in taskInfo.parts" :key="index">
									<!-- <view class="flex record-title">
											<text class="line1">{{ item.spareName }}</text>
										</view> -->
									<view class="flex flex-col justify-between flex-1 h-full record-content-body">
										<view class="record-content">
											<view class="record-item">
												<text>
													{{ item.spareName }}
												</text>
												<text>
													{{ item.spareCode }}
												</text>
											</view>
											<view class="record-item" style="align-items: center">
												<view class="">
													<u-number-box :min="0" buttonSize="26" v-model="item.sparePartNumber"></u-number-box>
												</view>
												<u-icon name="trash" color="red" size="20" style="margin-right: -2px" @click="handleDelete(index)"></u-icon>
											</view>
										</view>
									</view>
									<u-divider style="margin: 0"></u-divider>
								</view>
								<u-button
									class="addBtn1"
									type="primary"
									text="新增"
									@click="jump('/eam/equ/selectParts/index?assetKind=3')"
									style="height: 28px; width: 70px; text-align: center; justify-content: center; margin-left: 0; margin-top: 8px"
								></u-button>
							</view>
						</view>
					</view>

					<!-- <u-button class="addBtn1" size="small" type="primary" text="选择" @click="jump('/eam/equ/selectDevice/index')"></u-button> -->
					<!-- <view style="padding: 0 10px">
						<view v-show="taskInfo.repairStatus == 0" class="flex">
							<button type="primary" class="submit_btn flex-1" @click="openPrompt(taskInfo, 1)">应答</button>
						</view>
						<view v-show="taskInfo.repairStatus == 1" class="flex">
							<button type="primary" class="submit_btn flex-1" @click="openPrompt(taskInfo, 2)">开始维修</button>
						</view>
					</view> -->
					<!-- 已应答和维修中的情况，可以进行故障关闭操作，输入关闭原因 -->
				</u--form>
			</view>
			<view class="flex controls">
				<!-- 待确认状态下，可以进行确认和返修操作 -->

				<button v-show="props.isRead == 0" :disabled="finishLoading" class="submit_btn orange-btn orange-shadow flex-1" @click="submit(2)">维修完成</button>
				<button v-if="props.isRead == 0" :disabled="postLoading" :loading="postLoading" type="primary" class="submit_btn flex-1" @click="save(2)">保 存</button>
				<!-- 已应答和维修中的情况，可以进行故障关闭操作，输入关闭原因 -->
				<!-- <button v-show="taskInfo.repairStatus == 1 || taskInfo.repairStatus == 2" class="submit_btn grey_btn flex-1" @click="openPrompt(taskInfo, 6)">
					故障关闭
				</button> -->
			</view>
		</view>
		<!-- 开始时间选择picker弹窗 -->

		<!-- 树形选择器 -->
		<ba-tree-picker
			ref="personPicker"
			:multiple="true"
			@select-change="personChange"
			title="班组成员"
			:selectedData="showPersonValue"
			:localdata="personList"
			valueKey="memberId"
			textKey="memberName"
			childrenKey="nodes"
		/>
	</view>
</template>

<script lang="ts" setup>
import { nextTick, ref, toRefs, watch, reactive, computed, toRaw } from 'vue';
import { onShow, onPullDownRefresh, onLaunch, onBackPress } from '@dcloudio/uni-app';
import UploadImage from '@/components/upload-image-ssr.vue';
import PlannedDeviceInfo from '@/pages/eam/mold/plannedMaintenance/components/plannedDeviceInfo.vue';
import PlannedImageInfo from '@/pages/eam/mold/plannedMaintenance/components/plannedImageInfo .vue';
import RepairOrderInfo from '@/pages/eam/mold/repairOrderCreate/components/repairOrderInfo.vue';
import PlannedHandleInfo from '@/pages/eam/mold/plannedMaintenance/components/plannedHandleInfo.vue';
import { http } from '@/utils/http';
import { getSecondTime, getTimes, validateNumber, validateNumberCanNull } from '@/utils/common';
import { useUserStore } from '@/stores/useUserStore';
import { getCrewMemberListApi, getCrewListApi } from '@/api/jt-api';
import { useEamStore } from '@/stores/useEamStore';
import { useDictionaryStore } from '@/stores/useDictionaryStore';
import BaTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue';
import { CommonValue } from '@/types/type';
const props = defineProps({
	id: {
		type: String,
		default: ''
	},
	isRead: {
		type: String,
		default: '' // 1是查看
	},
	assetId: {
		// 模具Id
		type: String,
		default: ''
	},
	assetKind: {
		type: String,
		default: '3'
	},
	// 报修来源 按照字典表来 EamFaultSource
	repairSource: {
		type: String,
		default: '1'
	}
});

// 获取安全距离高度
const { safeAreaInsets } = uni.getSystemInfoSync();

// tag切换功能
const tagCurrent = ref(0);
function selectTagHandle(index) {
	tagCurrent.value = index;
}

// 获取当前页面实例
const pages = getCurrentPages();
// 获取当前页面的实例
const currentPage: any = pages[pages.length - 1];
// 获取页面路径
const pagePath = currentPage.$page.fullPath;

// 表单规则定义

const rules = reactive({
	assetName: [{ required: true, message: '请选择模具', trigger: 'blur' }],
	faultStatus: [{ required: true, message: '请选择故障状态', trigger: 'change' }],
	repairLevel: [{ required: true, message: '请选择故障等级', trigger: 'change' }],
	faultModeId: [],
	repairStartTime: [],
	repairEndTime: [],
	faultPhenomenon: [{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }],
	faultReason: [{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }],
	faultHandleMeasure: [
		{
			min: 1,
			max: 255,
			message: '长度在 1 到 255 个字符',
			trigger: 'blur'
		}
	],
	repairTime: [],
	repairUseTime: [
		{ required: true, message: '请输入维修用时(h）', trigger: 'blur' },
		// {
		// 	validator: validateNumberCanNull,
		// 	trigger: 'blur'
		// }
	],
	repairSituation: [
		{ required: true, message: '请输入维修情况说明', trigger: 'blur' },
		{
			min: 1,
			max: 255,
			message: '长度在 1 到 255 个字符',
			trigger: 'blur'
		}
	],
	otherProblem: [
		// { required: true, message: "维修中发现的其他问题", trigger: "blur" },
		{
			min: 1,
			max: 255,
			message: '长度在 1 到 255 个字符',
			trigger: 'blur'
		}
	],
	repairUserName: [{ min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }],
	repairTeamId: [{ message: '请选择维修班组', trigger: 'change' }],
	repairTeamUser: [{ message: '请选择维修人', trigger: 'change' }],
	sonsparePartNumber: [
		{
			validator: validateNumber,
			trigger: 'blur'
		}
	],
	maintainUser: [
		// { validator: validatePersons, trigger: "change" },
		{ required: true, message: '请输入维修人员', trigger: 'blur' },
		{
			min: 1,
			max: 255,
			message: '长度在 1 到 255 个字符',
			trigger: 'blur'
		}
	],
	fixAfterFiles: [{ validator: validateImages, trigger: 'change' }],
	fixBeforeFiles: [{ validator: validateImages, trigger: 'change' }]
});

function validatePersons(rule: any, value: any, callback: (a?: any) => {}) {
	if (taskInfo?.repairOrderPersons?.length == 0) {
		callback(new Error('请选择维修人员'));
	} else {
		callback();
	}
}

function validateImages(rule: any, value: any, callback: (a?: any) => {}) {
	if (taskInfo?.fixBeforeFiles?.length == 0) {
		callback(new Error('请选择维修前图片'));
	} else if (taskInfo?.fixAfterFiles?.length == 0) {
		callback(new Error('请选择维修后图片'));
	} else {
		callback();
	}
}

// 选择模具信息
const deviceList = computed(() => JSON.parse(useEamStore().deviceList));

// 网页跳转
function jump(item, id = '') {
	uni.navigateTo({
		url: id ? `/pages${item}?id=${id}` : `/pages${item}`,
		fail: () => {
			uni.showToast({
				title: '敬请期待',
				icon: 'error'
			});
		}
	});
}

// 跳转至备件页面
function jumpUrl(url) {
	uni.navigateTo({
		url: url,
		fail: () => {
			uni.showToast({
				title: '敬请期待',
				icon: 'error'
			});
		}
	});
}

// 是否折叠
const isCollapse = ref(false);

// 初始化页面，获取检查详情
let taskInfo = reactive<any>({
	id: '',
	// 模具信息
	assetId: '',
	assetName: '',
	assetCode: '',
	assetTypeName: '',
	assetModelNo: '',
	assetBrandName: '',
	usingDepartmentName: '',
	usingPersonName: '',
	locationName: '',
	// 故障信息
	images: [],
	executeFiles: [],
	faultStatus: '',
	repairLevel: '',
	remarks: '',
	memo: '',

	// 维修信息
	repairTeamId: '',
	repairTeamCode: '',
	repairTeamName: '',
	repairTeamText: '',

	repairTeamUser: '',
	repairTeamUserText: '',
	repairTeamUserName: '',
	repairTeamUserEmpNo: '',
	repairUseTime: '', // 维修用时

	// 以下为原生数据
	version: '',
	// assetTypeId: "",
	repairTime: '',
	repairUser: useUserStore().userInfo.userId,
	repairUserName: useUserStore().userInfo.userName,
	repairCode: '',
	// faultStatus: "",
	// repairLevel: "",
	// repairTeamId: "",
	// repairTeamUser: "",
	answerTime: '',
	repairStartTime: '',
	repairEndTime: '',
	repairStartTimeCode: '',
	repairEndTimeCode: '',
	faultMode: '',
	faultModeId: '',
	faultPhenomenon: '',
	faultPhenomenonId: '',
	faultReason: '',
	faultReasonId: '',
	faultPosition: '',
	faultPositionId: '',
	faultHandleMeasure: '',
	faultHandleMeasureId: '',
	parts: [],
	fixAfterFiles: [],
	fixBeforeFiles: [],
	repairSituation: '',
	repairStatus: '',
	outSourcing: '',
	createTime: '',
	createdUserId: '',
	createdUserName: '',
	lastUpdateTime: '',
	lastUpdatedUserId: '',
	lastUpdatedUserName: '',
	enabled: '',
	deleted: '',
	assetKind: props.assetKind || '1',
	repairSource: props.repairSource || '1',
	// 维修人员
	maintainUser:"",
	// 客户名称
	projectName:"",
	projectCode:""
});
const loading = ref(false);

// 摄像头参数设置
const capture = ref(['camera', 'album']);
const accept = ref('image');

// 获取现场图片
function getFixAfterFiles(list) {
	taskInfo.fixAfterFiles = list;
}
function getFixBeforeFiles(list) {
	taskInfo.fixBeforeFiles = list;
}

// 校验提交
const uForm = ref();

// 初始化 页面
let showPersonValue = ref([]);
let olderTaskInfo = reactive<any>({
	id: '',
	// 模具信息
	assetId: '',
	assetName: '',
	assetCode: '',
	assetTypeName: '',
	assetModelNo: '',
	assetBrandName: '',
	usingDepartmentName: '',
	usingPersonName: '',
	locationName: '',
	// 故障信息
	images: [],
	executeFiles: [],
	faultStatus: '',
	repairLevel: '',
	remarks: '',
	memo: '',

	// 维修信息
	repairTeamId: '',
	repairTeamCode: '',
	repairTeamName: '',
	repairTeamText: '',

	repairTeamUser: '',
	repairTeamUserText: '',
	repairTeamUserName: '',
	repairTeamUserEmpNo: '',
	repairUseTime: '', // 维修用时

	// 以下为原生数据
	version: '',
	// assetTypeId: "",
	repairTime: '',
	repairUser: useUserStore().userInfo.userId,
	repairUserName: useUserStore().userInfo.userName,
	repairCode: '',
	// faultStatus: "",
	// repairLevel: "",
	// repairTeamId: "",
	// repairTeamUser: "",
	answerTime: '',
	repairStartTime: '',
	repairEndTime: '',
	repairStartTimeCode: '',
	repairEndTimeCode: '',
	faultMode: '',
	faultModeId: '',
	faultPhenomenon: '',
	faultPhenomenonId: '',
	faultReason: '',
	faultReasonId: '',
	faultPosition: '',
	faultPositionId: '',
	faultHandleMeasure: '',
	faultHandleMeasureId: '',
	parts: [],
	fixAfterFiles: [],
	fixBeforeFiles: [],
	repairSituation: '',
	repairStatus: '',
	outSourcing: '',
	createTime: '',
	createdUserId: '',
	createdUserName: '',
	lastUpdateTime: '',
	lastUpdatedUserId: '',
	lastUpdatedUserName: '',
	enabled: '',
	deleted: '',
	assetKind: props.assetKind || '1',
	repairSource: props.repairSource || '1',
	maintainUser:"",
	projectName:"",
	projectCode:""
});
const person = ref('');
const planDto = ref([]);
async function initPage() {
	try {
		loading.value = true;
		const result: any = await http({
			method: 'GET',
			url: `/eam/eamplanrepairorder/get/${props.id}`,
			data: {
				assetKind: props.assetKind
			}
		}).finally(() => {
			uni.stopPullDownRefresh();
		});

		olderTaskInfo = Object.assign(olderTaskInfo, { ...result.data });

		await getPlan(olderTaskInfo.planId);
		taskInfo = Object.assign(taskInfo, {
			...result.data,
			images: result.data.images || [],
			executeFiles: result.data.executeFiles || [],
			parts: result.data.parts || [],

			repairStartTimeCode: result.data.repairStartTime ? Number(new Date(result.data.repairStartTime)) : '',
			repairEndTimeCode: result.data.repairEndTime ? Number(new Date(result.data.repairEndTime)) : '',
			fixAfterFiles1: JSON.parse(JSON.stringify(result.data.fixAfterFiles)),
			fixBeforeFiles1: JSON.parse(JSON.stringify(result.data.fixBeforeFiles))
		});
		taskInfo = JSON.parse(JSON.stringify(taskInfo));
		console.log("taskInfo", taskInfo);
		// if (taskInfo.repairTeamUserEmpNo) {
		// 	getMembers(taskInfo.repairTeamId);
		// 	taskInfo.repairTeamUserText =
		// 		taskInfo.repairTeamUserEmpNo + "-" + taskInfo.repairTeamUserName;
		// }
		// if (taskInfo.repairTeamCode) {
		// 	taskInfo.repairTeamText =
		// 		taskInfo.repairTeamCode + "-" + taskInfo.repairTeamName;
		// 	getMembers(taskInfo.repairTeamId);
		// }
		// 根据班组获取人员
		getPersonList();
		person.value = '';
		// 显示已选的名字
		// taskInfo.repairOrderPersons.forEach((item, index) => {
		// 	showPersonValue.value.push(item.personId);
		// 	// person.value+=item.personName
		// 	person.value = taskInfo.repairOrderPersons.length - 1 == index ? person.value + ' / ' + item.personName : person.value + ' / ' + item.personName;
		// });

		loading.value = false;

		nextTick(() => {
			selectTagHandle(1);
		});
	} catch (e) {
		console.log(e);
	}
}

async function getPlan(id) {
	await http({
		method: 'GET',
		url: `/eam/equrepairplan/get/${id}`
	})
		.then((res) => {
			planDto.value = [];
			res.data?.details?.forEach((item) => {
				item?.itemList?.forEach((item1) => {
					item1?.attachList?.forEach((item2) => {
						planDto.value?.push({...item2,remark:item1.remark});
					});
				});
			});
			console.log(planDto.value);
		})
		.finally(() => {
			uni.stopPullDownRefresh();
		});
}
// 清空数据
function clearInfo(arr) {
	if (arr[0] == 'repairOrderPersons') {
		taskInfo.repairOrderPersons = [];
		showPersonValue.value = [];
		person.value = '';
	} else {
		arr?.map((item) => {
			taskInfo[item] = '';
		});
	}
}
// 页面刷新
function refresh() {
	taskInfo.id = '';
	// 模具信息
	taskInfo.assetId = '';
	taskInfo.assetName = '';
	taskInfo.assetCode = '';
	taskInfo.assetTypeName = '';
	taskInfo.assetModelNo = '';
	taskInfo.assetBrandName = '';
	taskInfo.usingDepartmentName = '';
	taskInfo.usingPersonName = '';
	taskInfo.locationName = '';
	// 故障信
	taskInfo.images = [];
	taskInfo.executeFiles = [];
	taskInfo.faultStatus = '';
	taskInfo.repairLevel = '';
	taskInfo.remarks = '';
	taskInfo.memo = '';
	// 维修信息
	taskInfo.repairTeamId = '';
	taskInfo.repairTeamCode = '';
	taskInfo.repairTeamName = '';
	taskInfo.repairTeamText = '';

	taskInfo.repairTeamUser = '';
	taskInfo.repairTeamUserText = '';
	taskInfo.repairTeamUserName = '';
	taskInfo.repairTeamUserEmpNo = '';
	taskInfo.repairUseTime = ''; // 维修用时

	// 以下为原生数据
	taskInfo.version = '';
	// assetTypeId: "",
	taskInfo.repairTime = '';
	taskInfo.repairUser = useUserStore().userInfo.userId;
	taskInfo.repairUserName = useUserStore().userInfo.userName;
	taskInfo.repairCode = '';
	// faultStatus= ""
	// repairLevel= ""
	// repairTeamId= ""
	// repairTeamUser= ""
	taskInfo.answerTime = '';
	taskInfo.repairStartTime = '';
	taskInfo.repairEndTime = '';
	taskInfo.repairStartTimeCode = '';
	taskInfo.repairEndTimeCode = '';
	taskInfo.faultMode = '';
	taskInfo.faultModeId = '';
	taskInfo.faultPhenomenon = '';
	taskInfo.faultPhenomenonId = '';
	taskInfo.faultReason = '';
	taskInfo.faultReasonId = '';
	taskInfo.faultPosition = '';
	taskInfo.faultPositionId = '';
	taskInfo.faultHandleMeasure = '';
	taskInfo.faultHandleMeasureId = '';
	taskInfo.parts = [];
	taskInfo.fixAfterFiles = [];
	taskInfo.fixBeforeFiles = [];
	taskInfo.repairSituation = '';
	taskInfo.repairStatus = '';
	taskInfo.outSourcing = '';
	taskInfo.createTime = '';
	taskInfo.createdUserId = '';
	taskInfo.createdUserName = '';
	taskInfo.lastUpdateTime = '';
	taskInfo.lastUpdatedUserId = '';
	taskInfo.lastUpdatedUserName = '';
	taskInfo.enabled = '';
	taskInfo.deleted = '';
	taskInfo.assetKind = props.assetKind || '1';
	taskInfo.repairSource = props.repairSource || '1';
	taskInfo.maintainUser ="";
	taskInfo.projectName ="";
	taskInfo.projectCode ="";
	props.id && initPage();
}

// 下拉加载
onPullDownRefresh(() => {
	uni.showToast({
		title: 'onPullDownRefresh'
	});
	refresh();
});

// 页面显示回调
refresh();

// 过滤模具信息
function filterDeviceInfo(item) {
	taskInfo.parts.push({
		spareType: item.spareType,
		spareCode: item.spareCode,
		spareName: item.spareNmae,
		spareUnit: item.spareUnit,
		sparePartNumber: '',
		sparePartId: item.id
	});
}
/** 删除行 */
const handleDelete = (index: any) => {
	taskInfo.parts.splice(index, 1);
};
// 监控模具选择id
watch(
	() => deviceList,
	async (newVal) => {
		if (newVal.value[0]?.id) {
			filterDeviceInfo(newVal.value[0]);
		}
		setTimeout(() => {
			useEamStore().setDeviceList();
		}, 1000);
	},
	{
		deep: true,
		immediate: true
	}
);

//首次进入，新建状态，清空模具报修缓存
onShow(() => {
	// if (!props.id) {
	// 	useEamStore().setDeviceList();
	// }
});

// 选择班组成员
const personId = ref('');
const personPicker = ref();
function showPersonPicker() {
	personPicker.value._show();
}

// 获取位置列表
const personList = ref();
async function getPersonList() {
	const { data } = await http({
		method: 'POST',
		url: `/eam/eamteammember/getList`,
		data: { teamId: taskInfo.executeTeamId }
	});
	personList.value = data;
}
//监听选择（ids为数组）
// let showPersonValue = ref([]);
function personChange(ids, names) {
	personId.value = ids;
	taskInfo.repairOrderPersons = [];
	ids.forEach((item) => {
		personList.value.forEach((item1) => {
			if (item == item1.memberId) {
				taskInfo.repairOrderPersons.push({
					personId: item1.memberId,
					personName: item1.memberName,
					personEmpNo: item1.memberEmpNo,
					organiaztionId: item1.organizationId
				});
			}
		});
	});
	person.value = names ?? '';
	showPersonValue.value = ids;
}

// 清空数据
function clearPersonInfo() {
	personId.value = '';
	person.value = '';
	if (personPicker.value?._reTreeList) {
		personPicker.value._reTreeList();
	}
}

const finishLoading = ref(false);
const postLoading = ref(false);
function submit(type: number) {
	uForm.value
		.validate()
		.then(async () => {
			postLoading.value = true;
			finishLoading.value = true;
			personList.value.forEach((item) => {
				taskInfo.repairOrderPersons.forEach((item1, index) => {
					if (item.memberId == item1.personId) {
						taskInfo.repairOrderPersons[index].personEmpNo = item.memberEmpNo;
					}
				});
			});

			const result: any = await http({
				method: 'POST',
				url: `/eam/mouldplanrepairorder/finish`,
				data: taskInfo
			}).finally(() => {
				postLoading.value = false;
				finishLoading.value = false;
			});

			uni.showToast({
				title: `提交成功`
			});
			uni.navigateTo({
				url: `/pages/eam/mold/plannedMaintenance/index`
			});
			refresh();
		})
		.catch((e) => {
			console.log('catch', e);
		});
}
// 保存
async function save(type: number) {
	postLoading.value = true;
	finishLoading.value = true;
	personList.value.forEach((item) => {
		taskInfo.repairOrderPersons.forEach((item1, index) => {
			if (item.memberId == item1.personId) {
				taskInfo.repairOrderPersons[index].personEmpNo = item.memberEmpNo;
			}
		});
	});
	const result: any = await http({
		method: 'POST',
		url: `/eam/mouldplanrepairorder/save`,
		data: taskInfo
	}).finally(() => {
		postLoading.value = false;
		finishLoading.value = false;
	});
	uni.showToast({
		title: `保存成功！`
	});
	uni.navigateTo({
		url: `/pages/eam/mold/plannedMaintenance/index`
	});
	refresh();
}

onBackPress(() => {
	back1();
	return true;
});
const back1 = () => {
	uni.navigateTo({
		url: '/pages/eam/mold/plannedMaintenance/index'
	});
};
</script>

<style lang="scss" scoped>
.handle-ok {
	min-width: 75px;
	color: #19be6b;
}
.card {
	background-color: #fff;
	margin: 10px 10px;
	border-radius: 8px;
	padding: 12px 12px;
	transition: all 300ms ease;
	box-shadow: 0 2px 6px rgba(3, 121, 255, 0.05);
}

.overhidden {
	overflow: hidden;
}

uni-page-body {
	height: 100%;
	background-color: #fbfbff;
}

.u-divider {
	margin: 10px 0;
}

.baseForm {
	background-color: #fbfbff;
	display: block;

	padding-bottom: 50px;
}

.title {
	font-size: 16px;
	margin: 6px 0 14px;
	font-weight: bold;
	.u-icon {
		margin-right: 3px;
	}
}

.submit_btn {
	margin: 60rpx 20rpx;
	border-radius: 60rpx;
	height: 45px;
	font-size: 16px;
	line-height: 45px;
	box-shadow: 0 1px 10px rgba(3, 121, 255, 0.3);
}
.grey_btn {
	background-color: #fff !important;
	border: 1px solid #999;
	box-shadow: 0 1px 10px rgba(22, 37, 78, 0.08);
	color: #4f4f4f;
}

.searchScan {
	display: flex;
	height: 37px;
	padding: 12px 12px 0px;
	:deep(.u-input) {
		border: none;
		background-color: #fff !important;
		box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
	}
	.addBtn1 {
		width: 60px;
		height: 36px;
		margin-left: -3px !important;
		:deep(.u-button__text) {
			font-size: 14px !important;
		}
	}
}
:deep(.u-form-item__body) {
	padding: 4px 0 12px;
}
:deep(.u-number-box__input) {
	width: 60px !important;
}
:deep(.u-form-item) {
	.u-form-item__body__left__content__label {
		color: #a8b2bb;
		font-size: 14px;
		margin-bottom: 1px;
	}
	.u-form-item__body__left__content__required {
		font-size: 16px;
	}
	// 单选不可编辑样式
	.u-radio {
		.u-radio__icon-wrap--disabled {
			background-color: rgb(255, 255, 255) !important;
		}
		.u-radio__icon-wrap--disabled--checked {
			background-color: rgb(41, 121, 255) !important;
			border-color: rgb(41, 121, 255) !important;
			.u-icon__icon {
				color: #fff !important;
			}
		}
		.u-radio__text {
			color: #16254e !important;
			font-size: 14px !important;
		}
	}

	.u-textarea--disabled {
		background-color: #fff !important;
	}
	.uni-textarea-textarea {
		color: #16254e !important;
	}

	.input-box {
		width: 100%;
		border: 0.5px solid #dadbde !important;
		border-radius: 4px;
		.u-input {
			pointer-events: none;
			height: 34px;
			padding-left: 10px !important;
		}
		image {
			padding: 7px 6px;
			width: 20px;
			height: 20px;
		}
	}

	.input-box1 {
		width: 100%;
		border: 0.5px solid #dadbde !important;
		border-radius: 4px;
		.u-input {
			height: 34px;
			padding-left: 10px !important;
		}
		image {
			padding: 7px 6px;
			width: 20px;
			height: 20px;
		}
	}
}

.mt-10- {
	margin-top: -30px;
}

.controls {
	padding: 0 5px;
	position: fixed;
	bottom: 5px;
	left: 0;
	width: calc(100% - 10px);
	z-index: 99;
	.submit_btn {
		margin: 0px 5px;
		border-radius: 10px;
	}
}

// :deep(.repaire_tag_div) {
// 	width: 200px;
// 	margin: 0 auto;
// 	padding-top: 10px;
// 	display: flex;
// 	.u-subsection__bar--first {
// 	    border-top-left-radius: 20px;
// 	    border-bottom-left-radius: 20px;
// 	}
// 	.u-subsection__bar--last {
// 	    border-top-right-radius: 20px;
// 	    border-bottom-right-radius: 20px;
// 	}
// 	.u-subsection__item--first {
// 		border-top-left-radius: 20px;
// 		border-bottom-left-radius: 20px;
// 	}
// 	.u-subsection__item--last {
// 		border-top-right-radius: 20px;
// 		border-bottom-right-radius: 20px;
// 		background-color: #fff;
// 	}
// }
.repaire_tag_div {
	display: flex;
	justify-content: center;
	width: 100%;
	.repaire_tag {
		width: 200px;
		padding-top: 10px;
		display: flex;
		.tag_item {
			flex: 1;
			border: 1px solid #0379ff;
			background-color: #fff;
			text-align: center;
			font-size: 14px;
			color: #0379ff;
			padding: 5px 12px;
		}
		.tag_item:nth-child(1) {
			border-top-left-radius: 20px;
			border-bottom-left-radius: 20px;
		}
		.tag_item:nth-last-child(1) {
			border-top-right-radius: 20px;
			border-bottom-right-radius: 20px;
		}
		.active_tag {
			background-color: #0379ff !important;
			color: #fff !important;
			font-weight: bold !important;
		}
	}
}
:deep(.control-picker) {
	.u-transition {
		z-index: 1000 !important;
	}
}
:deep(.crew-picker) {
	.u-transition {
		z-index: 1001 !important;
	}
}
:deep(.member-picker) {
	.u-transition {
		z-index: 1001 !important;
	}
}
</style>
